package yzy.ecps.controller;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import yzy.ecps.utils.EcpsUtils;
import yzy.ecps.utils.FileUploadUtil;
import yzy.ecps.utils.UploadResponse;

@Controller
@RequestMapping("/file")
public class FileUploadController {
	
	/**
	 * 接收并响应浏览器发送的上传品牌图片的ajax请求
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/uploadBrandPic.do")
	public void uploadBrandPic(HttpServletRequest request,HttpServletResponse response) throws IOException{
		uploadPic(request,"pics/brand");
		
		JSONObject json = new JSONObject();
		json.accumulate("realPath", FileUploadUtil.realPath);
		json.accumulate("relativePath", FileUploadUtil.relativePath);
		response.getWriter().write(json.toString());
	}
	
	/**
	 * 接收并响应浏览器发送的上传商品图片的ajax请求
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/uploadGoodsPic.do")
	public void uploadGoodsPic(HttpServletRequest request,HttpServletResponse response) throws IOException{
		uploadPic(request,"pics/goods");
		
		JSONObject json = new JSONObject();
		json.accumulate("realPath", FileUploadUtil.realPath);
		json.accumulate("relativePath", FileUploadUtil.relativePath);
		response.getWriter().write(json.toString());
	}
	
	/**
	 * 接收并处理通过富文本编辑器上传的商品描述图片的请求
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/uploadForFck.do")
	public void uploadForFck(HttpServletRequest request,HttpServletResponse response) throws IOException{
		uploadPic(request,"pics/goods_desc");
		
		UploadResponse ur = new UploadResponse(UploadResponse.EN_OK,FileUploadUtil.realPath);
		response.getWriter().print(ur);
	}
	
	/**
	 * 解析请求上传的图片文件，上传到指定的服务器同时设置图片的相对路径和绝对路径
	 * @param request
	 * @param picDir
	 * @throws IOException
	 */
	private void uploadPic(HttpServletRequest request,String picDir) throws IOException{
		//将请求转换成复杂类型的请求
		MultipartHttpServletRequest ms = (MultipartHttpServletRequest) request;
		//获取请求中的名称
		Iterator<String> fileNames = ms.getFileNames();
		//根据第一个名称获取对应的文件
		MultipartFile file = ms.getFile(fileNames.next());
		//获文件服务器的路径
		String serverPath = EcpsUtils.getValueByKeyFormSysProperties("fileserver_path");
		//上传文件到指定的路径并设置图片的相对和绝对路径
		FileUploadUtil.uploadPicAndSetPicPathes(file, serverPath, picDir);
		
	}
	
}
